<template>
  <div class="login-container">
    <div class="head" v-if="checkShow()"></div>
    <div class="main" v-if="showModule === 0">
      <div class="tabs">
        <div
          v-for="item in tabs"
          :class="['tabs-item', tabsActive === item.value && 'active']"
          :key="item.value"
          @click="tabsClick(item)"
        >
          {{ item.label }}
        </div>
      </div>
      <el-form
        class="form-main"
        :style="{ marginTop: processActive ? '30px' : '40px' }"
        ref="loginForm"
        :model="formData"
      >
        <el-form-item :rules="$validate.required()" prop="username">
          <el-input
            v-model="formData.username"
            :placeholder="usernamePlaceholder"
          >
            <img slot="prefix" src="@/assets/img/login/user_icon.png" alt="" />
          </el-input>
        </el-form-item>
        <el-form-item :rules="$validate.required()" prop="password">
          <el-input
            :type="passwordShow ? 'text' : 'password'"
            v-model="formData.password"
            placeholder="请输入密码"
          >
            <img
              slot="prefix"
              src="@/assets/img/login/password_icon.png"
              alt=""
            />
            <img
              v-if="passwordShow"
              slot="suffix"
              src="@/assets/img/login/show_password_icon.png"
              @click="passwordShow = !passwordShow"
              alt=""
            />
            <img
              v-else
              slot="suffix"
              src="@/assets/img/login/hide_password_icon.png"
              @click="passwordShow = !passwordShow"
              alt=""
            />
          </el-input>
        </el-form-item>
        <el-form-item :rules="$validate.required()" prop="captcha">
          <el-input
              v-model="formData.captcha"
              class="verificationCodeInput"
              size="large"
              type="text"
              placeholder="请输入验证码"
          >
            <el-icon
                slot="prefix"
                type=""
                :style="{ color: 'rgba(0,0,0,.25)' }"
            />
          </el-input>

        </el-form-item>
        <img
            v-if="requestCodeSuccess"
            style="margin-top: 2px"
            :src="randCodeImage"
            @click="handleChangeCheckCode"
        />
        <img
            v-else
            style="margin-top: 2px"
            src="../../assets/checkcode.png"
            @click="handleChangeCheckCode"
        />
      </el-form>

      <div class="active-line">
        <div class="active-line-item item2" v-if="!loginType">
          <span @click="process">{{
            processActive ? '用户登录' : '审核人员登录'
          }}</span>
        </div>
      </div>
      <div class="submit" @click="submit">登录</div>
<!--&lt;!&ndash;      <div class="foot-text" v-if="!processActive" @click="register">&ndash;&gt;-->
<!--&lt;!&ndash;        立即注册账号&ndash;&gt;-->
<!--&lt;!&ndash;      </div>&ndash;&gt;-->
<!--    </div>-->
<!--    <userRegister-->
<!--      v-show="showModule === 1"-->
<!--      ref="userRegister"-->
<!--      @login="showModule = 0"-->
<!--    />-->
<!--    <legalRegister-->
<!--      v-show="showModule === 2"-->
<!--      ref="legalRegister"-->
<!--      @login="showModule = 0"-->
<!--    />-->
  </div>
  </div>
</template>

<script>
import userApi from '@/api/user';
import { 
  // encrypt, 
  decrypt } from '@/utils/sms4util';
import { menuUser, menuCompany, menuOperator } from '@/setting/menu';
export default {
  name: 'Login',
  props: {
    loginType: {
      type: String,
    },
    token: {
      type: String,
    },
  },
  data() {
    return {
      tabsActive: 1,
      passwordShow: false,
      formData: {
        username: '',
        password: '',
        captcha: '',
      },
      codeSuccess: false,
      showModule: 0,
      processActive: false,
      processValue: 3,
      menuMap: {
        3: menuOperator.menuAcceptor,
        4: menuOperator.menuAcceptor,
        5: menuOperator.menuReviewer,
        6: menuOperator.menuReviewer,
        7: menuOperator.menuManage,
        8: menuOperator.menuAcceptor,
        9: menuOperator.menuReviewer
      },
      requestCodeSuccess: false,
      randCodeImage: '',
      nowKey: '',
    };
  },
  computed: {
    tabs() {
      if (this.processActive) {
        return [
          { label: '个人审核登录', value: 1 },
          { label: '单位审核登录', value: 2 },
        ];
      } else {
        if (this.loginType == 1) {
          return [{ label: '个人用户登录', value: 1 }];
        } else if (this.loginType == 2) {
          return [{ label: '法人或经办人登录', value: 2 }];
        } else {
          return [
            { label: '个人用户登录', value: 1 },
            { label: '法人或经办人登录', value: 2 },
          ];
        }
      }
    },
    processOptions() {
      return [
        { label: '受理人员', value: 3 },
        { label: '审核人员', value: 5 },
      ];
    },
    usernamePlaceholder() {
      if (!this.processActive) {
        if (this.tabsActive === 1) {
          return '手机号/身份证';
        } else {
          return '用户名';
        }
      } else {
        return '用户名';
      }
    },
  },
  created() {
    // token登录(sso)
    if (this.token) {
      userApi.loginWithToken({ token: this.token }).then((res) => {
        const { token, sysAllDictItems, userInfo } = res;
        const decryptUserInfo = {
          ...userInfo,
          phone: userInfo.phone ? decrypt(userInfo.phone) : '',
          paperCode: userInfo.paperCode ? decrypt(userInfo.paperCode) : '',
          unitTel: userInfo.unitTel ? decrypt(userInfo.unitTel) : '',
          creditCode: userInfo.creditCode ? decrypt(userInfo.creditCode) : '',
        }
        let menuData;
        // 获取菜单
        if (userInfo.userType == 1) {
          menuData = menuUser;
        } else if (userInfo.userType == 2) {
          menuData = menuCompany;
        } else {
          let roleArr = userInfo.userType.split(',');
          let roleMenu = [];
          roleArr.forEach((item) => {
            roleMenu = [...roleMenu, ...this.menuMap[+item]];
          });
          menuData = [...roleMenu, ...menuOperator.default];
          menuData.sort((a, b) => a.key - b.key);
        }
        let menu = new Set([
          ...menuData,
          { name: '退出', key: '999', icon: 'icon5', path: '/login' },
        ]);
        // 设置数据
        this.$store.commit('dict/setDict', sysAllDictItems);
        this.$store.commit('user/setMenuList', [...menu]);
        this.$store.commit('user/setToken', token);
        this.$store.commit('user/setUserInfo', decryptUserInfo);

        // sso data
        sessionStorage.setItem('userId', userInfo.id);
        if (userInfo.userType == 1 || userInfo.userType == 2) {
          userApi.getUserInfo({
            id: userInfo.id,
            type: userInfo.userType,
          }).then((res) => {
            this.$store.commit('user/setUserQua', res?.sysUnitQua);
            this.$router.push(
                menuData?.[0]?.path ?? menuData?.[0]?.children?.[0]?.path,
            );
          });
        } else {
          this.$router.push(
              menuData?.[0]?.path ?? menuData?.[0]?.children?.[0]?.path,
          );
        }
      });
    }
    if (this.loginType == 2) {
      this.tabsActive = 2;
    }
    this.handleChangeCheckCode();
  },
  methods: {
    checkShow() {
        return process.env.NODE_ENV === 'production';
    },
    async submit() {
      // 2023.10.29以下为模拟登录代码
      let roleArr = [3];
      let roleMenu = [];
      roleArr.forEach((item) => {
        roleMenu = [...roleMenu, ...this.menuMap[+item]];
      });
      // 获取菜单
      let menuData;
      menuData = [...roleMenu, ...menuOperator.default];
      menuData.sort((a, b) => a.key - b.key);

      const params = {
      }

      const { token, sysAllDictItems, userInfo, manual } = params

      const decryptUserInfo = {
          ...userInfo,
          phone: userInfo && userInfo.phone ? decrypt(userInfo.phone) : '',
          paperCode: userInfo && userInfo.paperCode ? decrypt(userInfo.paperCode) : '',
          unitTel: userInfo && userInfo.unitTel ? decrypt(userInfo.unitTel) : '',
          creditCode: userInfo && userInfo.creditCode ? decrypt(userInfo.creditCode) : '',
      }

      let menu = new Set([
        ...menuData,
        { name: '退出', key: '999', icon: 'icon5', path: '/login' },
      ]);
      console.log(menu,'经办人菜单')
      // 设置数据
      this.$store.commit('dict/setDict', sysAllDictItems || '');
      this.$store.commit('user/setMenuList', [...menu]);
      this.$store.commit('user/setToken', token || '1322');
      this.$store.commit('user/setUserInfo', decryptUserInfo);
      this.$store.commit('user/setManual', manual || '');
      // 22-11-11: fit sso login
      sessionStorage.setItem('userId', userInfo?.id || 'id1111');
      this.$router.push(
        menuData?.[0]?.path ?? menuData?.[0]?.children?.[0]?.path,
      );
      // 2023.10.29以下为正式登录代码
      // try {
      //   // 验证
      //   await this.$validate.checkValidate(this.$refs.loginForm);
      //   // if (!this.codeSuccess) {
      //   //   this.$message.warning('请先进行图片验证！');
      //   //   return;
      //   // }
      //   let loginMode;
      //   if (this.processActive) {
      //     loginMode =
      //       this.tabsActive === 1 ? 5 : 6;
      //   } else {
      //     loginMode = this.tabsActive;
      //   }
      //   let params = {
      //     ...this.formData,
      //     checkKey: this.nowKey,
      //     password: encrypt(this.formData.password),
      //     loginMode: loginMode,
      //   };
      //   // 登录
      //   const { token, sysAllDictItems, userInfo, manual } =
      //     await userApi.login(params);
      //   console.log('userInfo', userInfo);
      //   const decryptUserInfo = {
      //     ...userInfo,
      //     phone: userInfo.phone ? decrypt(userInfo.phone) : '',
      //     paperCode: userInfo.paperCode ? decrypt(userInfo.paperCode) : '',
      //     unitTel: userInfo.unitTel ? decrypt(userInfo.unitTel) : '',
      //     creditCode: userInfo.creditCode ? decrypt(userInfo.creditCode) : '',
      //   }
      //   // 获取菜单
      //   let menuData;
      //   if (userInfo.userType == 1) {
      //     menuData = menuUser;
      //   } else if (userInfo.userType == 2) {
      //     menuData = menuCompany;
      //   } else {
      //     let roleArr = userInfo.userType.split(',');
      //     let roleMenu = [];
      //     roleArr.forEach((item) => {
      //       roleMenu = [...roleMenu, ...this.menuMap[+item]];
      //     });
      //     menuData = [...roleMenu, ...menuOperator.default];
      //     menuData.sort((a, b) => a.key - b.key);
      //   }
      //   let menu = new Set([
      //     ...menuData,
      //     { name: '退出', key: '999', icon: 'icon5', path: '/login' },
      //   ]);
      //   // 设置数据
      //   this.$store.commit('dict/setDict', sysAllDictItems);
      //   this.$store.commit('user/setMenuList', [...menu]);
      //   this.$store.commit('user/setToken', token);
      //   this.$store.commit('user/setUserInfo', decryptUserInfo);
      //   this.$store.commit('user/setManual', manual);
      //   // 22-11-11: fit sso login
      //   sessionStorage.setItem('userId', userInfo.id);
      //   this.$router.push(
      //     menuData?.[0]?.path ?? menuData?.[0]?.children?.[0]?.path,
      //   );
      // } catch (error) {
      //   this.picCodeReset();
      //   console.log(error);
      // }
    },
    successVerify() {
      this.codeSuccess = true;
    },
    // 重置滑块
    picCodeReset() {
      if (this.codeSuccess) {
        this.codeSuccess = false;
        this.$refs.slideblock.onReset();
      }
    },
    // 注册
    register() {
      if (this.tabsActive == 1) {
        this.showModule = 1;
        this.$refs.userRegister.init();
      } else {
        this.showModule = 2;
        this.$refs.legalRegister.init();
      }
    },
    //
    process() {
      this.processValue = 3;
      this.processActive = !this.processActive;
      this.picCodeReset();
      this.resetForm();
    },
    resetForm() {
      this.formData = {
        username: '',
        password: '',
      };
    },
    tabsClick(item) {
      this.tabsActive = item.value;
      this.picCodeReset();
      this.resetForm();
    },
    handleChangeCheckCode() {
      this.nowKey = new Date().getTime()
      this.formData.captcha = ''
      userApi.getCode(this.nowKey)
          .then(res => {
            if (res) {
              this.randCodeImage = res
              this.requestCodeSuccess = true
            } else {
              this.requestCodeSuccess = false
            }
          })
          .catch(() => {
            this.requestCodeSuccess = false
          })
    }
  },
};
</script>
<style lang="scss" scoped>
.login-container {
  width: 100%;
  height: 100%;
  min-width: 1620px;
  background-image: url('~@/assets/img/login/big_bg.png');
  background-size: 100% 100%;
  background-position: center;
  display: flex;
  justify-content: center;
  align-items: center;
  .head {
    position: absolute;
    top: 0px;
    left: 0px;
    width: 100%;
    min-width: 1620px;
    height: 96px;
    background: url('~@/assets/img/login/head.png') 100% 100% no-repeat;
    background-position: center;
  }
  .main {
    width: 514px;
    height: 578px;
    background: url('~@/assets/img/login/form_bg.png') 100% 100% no-repeat;
    padding: 0px 70px 0px 74px;
    display: flex;
    flex-direction: column;
    align-items: center;

    .tabs {
      margin-top: 80px;
      width: 100%;
      font-size: 24px;
      display: flex;
      justify-content: space-evenly;
      align-items: center;
      .tabs-item {
        font-size: 18px;
        font-family: PingFangSC-Regular, PingFang SC;
        font-weight: 400;
        color: #333;
        cursor: pointer;
        &.active {
          font-weight: 600;
          color: #1c92ea;
        }
      }
    }
    .form-main {
      width: 100%;
      ::v-deep {
        .el-input__prefix,
        .el-input__suffix,
        .el-input__suffix-inner {
          display: flex;
          align-items: center;
        }
        input {
          height: 40px !important;
          line-height: 40px !important;
          padding-left: 40px;
          background-color: rgba(255, 255, 255, 0.52);
          border-radius: 3px;
          border: 1px solid #ffffff;
        }
      }
    }
    .active-line {
      margin-top: 22px;
      width: 100%;
      display: flex;
      justify-content: space-between;
      .active-line-item {
        font-size: 14px;
        color: #fff;
        cursor: pointer;
      }
      .item2 {
        flex: 1;
        text-align: right;
      }
    }
    .submit {
      margin-top: 54px;
      width: 100%;
      height: 40px;
      line-height: 40px;
      border-radius: 4px;
      text-align: center;
      color: #fff;
      letter-spacing: 6px;
      background: url('~@/assets/img/login/btn_bg.png') 100% 100% no-repeat;
      background-position: center;
      cursor: pointer;
    }
    .foot-text {
      margin-top: 50px;
      font-size: 16px;
      color: #b6e3ff;
      cursor: pointer;
    }
  }
}
</style>
